// index.js
const express = require('express');
const UserModel = require('./userModel');
const bodyParser = require('body-parser');
const cors = require("cors");
const db = require('./db');

const app = express();
app.use(bodyParser.json());
// 允许所有域名访问
app.use(cors());

// 用户注册
app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    console.log('Missing username or password'); // 打印缺失信息
    return res.status(400).send('Username and password are required');
  }

  try {
    console.log(`Attempting to register user: ${username}`); // 打印尝试注册信息

    const result = await UserModel.register(username, password);
    
    if (result.success) {
      console.log(`User registered: ${username}`); // 打印注册成功信息
      res.status(201).send('User registered');
    } else if (result.success === false && result.message === '用户名已存在') {
      console.log(`Username already exists: ${username}`); // 打印用户名已存在信息
      res.status(400).send('Username already exists');
    } else {
      console.log('Registration failed for an unknown reason'); // 打印未知错误信息
      res.status(400).send('Registration failed');
    }
  } catch (error) {
    console.error('Registration error:', error); // 打印注册错误信息
    res.status(500).send('Error registering user');
  }
});

// 用户登录
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).send('Username and password are required');
  }

  const user = await UserModel.login(username, password);
  if (user) {
    // 登录成功，返回成功消息
    res.status(200).send({ message: 'User logged in' });
  } else {
    // 用户名或密码错误
    res.status(401).send('Username or password is incorrect');
  }
});

//获取用户信息
app.get('/get-user-info', async (req, res) => {
  // 打印整个 req.query 对象
  console.log('Received query parameters:', req.query);
  const { username } = req.query;
  // 打印前端传入的 username 参数
  console.log('Received username:', username);
  if (!username) {
    return res.status(400).send('Username parameter is required');
  }

  try {
    const [rows] = await db.execute(
      'SELECT * FROM user WHERE username = ?',
      [username]
    );

    if (rows.length > 0) {
      const userInfo = rows[0];
      res.json(userInfo);
    } else {
      res.status(404).send('User not found');
    }
  } catch (error) {
    console.error('Error getting user info:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 存储用户正确单词个数
app.post('/store-correct-words', async (req, res) => {
  const { username, correctWordsCount } = req.body;
  console.info(req.body)
  if (!username || correctWordsCount === undefined) {
    return res.status(400).send('Username and correctWordsCount are required');
  }

  try {
    // 假设你有一个方法来更新用户正确单词个数
    const result = await db.execute(
      'UPDATE user SET correct_queries = ? WHERE username = ?',
      [correctWordsCount, username]
    );

    if (result.affectedRows > 0) {
      res.status(404).send('Correct words count updated successfully');
    } else {
      res.status(200).send('User not found or correct words count not updated');
    }
  } catch (error) {
    console.error('Error storing correct words count:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 标记单词为已学习
app.post('/mark-word-studied', async (req, res) => {
  const { username, wordId } = req.body;
  
  try {
    // 获取用户ID
    const [userRows] = await db.execute(
      'SELECT id FROM user WHERE username = ?',
      [username]
    );
    
    if (userRows.length === 0) {
      return res.status(404).send('User not found');
    }
    
    const userId = userRows[0].id;
    const now = new Date();
    // 设置下次复习时间为24小时后
    const nextReviewTime = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    
    // 插入或更新学习记录
    await db.execute(
      `INSERT INTO user_word_study (user_id, word_id, review_count, next_review_time, last_review_time) 
       VALUES (?, ?, 1, ?, ?) 
       ON DUPLICATE KEY UPDATE 
       review_count = review_count + 1,
       next_review_time = ?,
       last_review_time = ?`,
      [userId, wordId, nextReviewTime, now, nextReviewTime, now]
    );
    
    res.status(200).send('Word marked as studied');
  } catch (error) {
    console.error('Error marking word as studied:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 获取需要复习的单词
app.get('/review-words', async (req, res) => {
  const { username } = req.query;
  
  try {
    // 获取用户ID
    const [userRows] = await db.execute(
      'SELECT id FROM user WHERE username = ?',
      [username]
    );
    
    if (userRows.length === 0) {
      return res.status(404).send('User not found');
    }
    
    const userId = userRows[0].id;
    const now = new Date();
    
    // 获取需要复习的单词
    const [words] = await db.execute(
      `SELECT w.*, uws.review_count, uws.next_review_time 
       FROM words w 
       JOIN user_word_study uws ON w.id = uws.word_id 
       WHERE uws.user_id = ? 
       AND uws.mastered = FALSE 
       AND uws.next_review_time <= ?
       ORDER BY uws.next_review_time ASC`,
      [userId, now]
    );
    
    res.json(words);
  } catch (error) {
    console.error('Error getting review words:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 标记单词为已掌握
app.post('/mark-word-mastered', async (req, res) => {
  const { username, wordId } = req.body;
  
  try {
    // 获取用户ID
    const [userRows] = await db.execute(
      'SELECT id FROM user WHERE username = ?',
      [username]
    );
    
    if (userRows.length === 0) {
      return res.status(404).send('User not found');
    }
    
    const userId = userRows[0].id;
    
    // 更新单词状态为已掌握
    await db.execute(
      'UPDATE user_word_study SET mastered = TRUE WHERE user_id = ? AND word_id = ?',
      [userId, wordId]
    );
    
    res.status(200).send('Word marked as mastered');
  } catch (error) {
    console.error('Error marking word as mastered:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 获取用户的学习统计
app.get('/study-stats', async (req, res) => {
  const { username } = req.query;
  
  try {
    // 获取用户ID
    const [userRows] = await db.execute(
      'SELECT id FROM user WHERE username = ?',
      [username]
    );
    
    if (userRows.length === 0) {
      return res.status(404).send('User not found');
    }
    
    const userId = userRows[0].id;
    
    // 获取统计信息
    const [stats] = await db.execute(
      `SELECT 
        COUNT(*) as total_words,
        SUM(CASE WHEN mastered = TRUE THEN 1 ELSE 0 END) as mastered_words,
        AVG(review_count) as avg_reviews
       FROM user_word_study 
       WHERE user_id = ?`,
      [userId]
    );
    
    res.json(stats[0]);
  } catch (error) {
    console.error('Error getting study stats:', error);
    res.status(500).send('Internal Server Error');
  }
});

const PORT = process.env.PORT || 3001;

app.listen(PORT, '0.0.0.0', () => console.log(`Server running on port ${PORT}`));